package com.ruoyi.system.api.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.BatchLogMapper;
import com.ruoyi.system.api.mapper.PlanDetailsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.mapper.ServiceLogMapper;
import com.ruoyi.system.api.service.IServiceLogService;
import com.ruoyi.common.core.text.Convert;

/**
 * 服务日志 与服务1对1关联st_plan_detailsService业务层处理
 * 
 * @author shihx
 * @date 2020-03-09
 */
@Service
public class ServiceLogServiceImpl implements IServiceLogService 
{
    @Autowired
    private ServiceLogMapper serviceLogMapper;

    @Autowired
    private BatchLogMapper batchLogMapper;

    @Autowired
    private PlanDetailsMapper planDetailsMapper;


    /**
     * 查询服务日志 与服务1对1关联st_plan_details
     * 
     * @param id 服务日志 与服务1对1关联st_plan_detailsID
     * @return 服务日志 与服务1对1关联st_plan_details
     */
    @Override
    public ServiceLog selectServiceLogById(Long id)
    {
         ServiceLog serviceLog =  serviceLogMapper.selectServiceLogById(id);
        List<Map<String,String>> infoList =  serviceLogMapper.selectReportInfoByLogId(id);
        String synFlag = "0";
        for(Map<String,String> map:infoList){
            if(StringUtils.equals("1",map.get("sync_flag"))){
                synFlag="1";
                break;
            }
        }
        serviceLog.setSyncFlag(synFlag);
        return serviceLog;
    }

    /**
     * 查询服务日志 与服务1对1关联st_plan_details列表
     * 
     * @param serviceLog 服务日志 与服务1对1关联st_plan_details
     * @return 服务日志 与服务1对1关联st_plan_details
     */
    @Override
    public List<ServiceLog> selectServiceLogList(ServiceLog serviceLog)
    {
        List<ServiceLog> listLog = serviceLogMapper.selectServiceLogList(serviceLog);
        for(ServiceLog serviceLog1:listLog){
            if(StringUtils.isEmpty(serviceLog1.getReportId())){
                serviceLog1.setReportId("");
            }
        }
        return listLog;

    }
    public List<ServiceLog> selectUnRelationServiceLogList(ServiceLog serviceLog){
        List<ServiceLog> listLog = serviceLogMapper.selectUnRelationServiceLogList(serviceLog);
        for(ServiceLog serviceLog1:listLog){
            if(StringUtils.isEmpty(serviceLog1.getReportId())){
                serviceLog1.setReportId("");
            }
        }
        return listLog;
    }
    /**
     * 新增服务日志 与服务1对1关联st_plan_details
     * 
     * @param serviceLog 服务日志 与服务1对1关联st_plan_details
     * @return 结果
     */
    @Override
    public int insertServiceLog(ServiceLog serviceLog)
    {
        serviceLog.setCreateTime(DateUtils.getNowDate());
        return serviceLogMapper.insertServiceLog(serviceLog);
    }

    /**
     * 修改服务日志 与服务1对1关联st_plan_details
     * 
     * @param serviceLog 服务日志 与服务1对1关联st_plan_details
     * @return 结果
     */
    @Override
    public int updateServiceLog(ServiceLog serviceLog)
    {
        serviceLog.setUpdateTime(DateUtils.getNowDate());
        return serviceLogMapper.updateServiceLog(serviceLog);
    }

    /**
     * 删除服务日志 与服务1对1关联st_plan_details对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteServiceLogByIds(String ids)
    {
        return serviceLogMapper.deleteServiceLogByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除服务日志 与服务1对1关联st_plan_details信息
     * 
     * @param id 服务日志 与服务1对1关联st_plan_detailsID
     * @return 结果
     */
    @Override
    public int deleteServiceLogById(Long id)
    {
        return serviceLogMapper.deleteServiceLogById(id);
    }

    @Override
    public ResponseWithData<?> saveServiceLog(ServiceLogVo serviceLogVo) throws Exception{
        String[] sns = serviceLogVo.getServiceNoticeIds().split(",");
        String[] ps = serviceLogVo.getPlanIds().split(",");
        String[] snos = serviceLogVo.getServiceNos().split(",");
        // 关联的日志用一个时间方便后续查询
        Date date = new Date();
        for(int i=0;i<sns.length;i++){
            /** 更新计划详情表 */

            /**  20200410093800 经过沟通此段代码无用
             *   代码删除
             *   YZG
             *
                PlanDetails planDetails = new PlanDetails();
                planDetails.setId(Long.parseLong(ps[i]));
                planDetails.setSignOff("1");
                planDetails.setSignOffTime(date);
                if(StringUtils.isNotEmpty(serviceLogVo.getLongitude())){
                    planDetails.setSignOffLon(Double.parseDouble(serviceLogVo.getLongitude()));
                }
                if(StringUtils.isNotEmpty(serviceLogVo.getLatitude())){
                    planDetails.setSignOffLat(Double.parseDouble(serviceLogVo.getLatitude()));
                }
                planDetails.setUpdateTime(new Date());
                planDetailsMapper.updateStPlanDetails(planDetails);
            */
            /******更新计划****/
            Long currPlanId = new Long(ps[i]);
            PlanDetails planDetailsCurry= planDetailsMapper.selectStPlanDetailsById(currPlanId);

            Long lastPlanId;
            if(planDetailsCurry!=null){
                // 如果单子未 已接收状态
                if("1".equals(planDetailsCurry.getState())){
                    //最后一个状态是不是1，
                    PlanDetails planDetails = getPlanDetailsListStateNotOne(planDetailsCurry.getFseId(), planDetailsCurry.getServiceNoticeId());
                    if(planDetails==null){
                        //没找到状态非1的计划
                        return new ResponseWithData<>().success().msg("添加日志失败").code(201);
                    }
                    else {
                        lastPlanId = planDetails.getId();
                    }
                }
                else {
                    //状态非1
                    lastPlanId= currPlanId;
                }
            }
            else {
                //根据计划id没找到计划信息
                return new ResponseWithData<>().success().msg("添加日志失败").code(201);
            }

            PlanDetails logplanDetails = new PlanDetails();
            logplanDetails.setId(lastPlanId);
            logplanDetails.setFillInLog("1");
            logplanDetails.setUpdateTime(new Date());
            planDetailsMapper.updateStPlanDetails(logplanDetails);


            /** 新增服务日志表 */
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            ServiceLog serviceLog = new ServiceLog();
            serviceLog.setServiceNoticeId(Long.parseLong(sns[i]));
            serviceLog.setServiceNo(snos[i]);
            serviceLog.setFseId(serviceLogVo.getFseId());
            serviceLog.setStPlanId(lastPlanId);

            //判断填写日志次数（先查询列表最近一次，隔天flag+1）
/*            List<ServiceLog> logList = serviceLogMapper.selectServiceLogList(serviceLog);
            if(logList.size() > 0){
                int day = DateUtils.caculateTotalTime(sdf.format(logList.get(0).getCreateTime()),sdf.format(new Date()));
                if(day > 1){
                    serviceLog.setFlag(logList.get(0).getFlag() + 1);
                }else{
                    serviceLog.setFlag(logList.get(0).getFlag());
                }
            }else{
                serviceLog.setFlag(1);
            }*/

            serviceLog.setDepartureTime(serviceLogVo.getDepartureTime());
            serviceLog.setFseName(serviceLogVo.getFseName());
            serviceLog.setAcceptTime(sdf1.parse(serviceLogVo.getAcceptTime().trim()));
            serviceLog.setArriveTime(sdf1.parse(serviceLogVo.getArriveTime().trim()));
            serviceLog.setStartTime(sdf1.parse(serviceLogVo.getStartTime().trim()));
            serviceLog.setEndTime(sdf1.parse(serviceLogVo.getEndTime().trim()));

            /* 批量拆分日志时间*/
            String splitFlag=serviceLogVo.getSplitFlag();
            if("1".equals(splitFlag)){

                double workHour= new Double(serviceLogVo.getWorkHour().trim());
                double splitworkHour=workHour/sns.length;
                serviceLog.setWorkHour(splitworkHour);
                double journeyHour= new Double(serviceLogVo.getJourneyHour().trim());
                double splitjourneyHour=journeyHour/sns.length;
                serviceLog.setJourneyHour(splitjourneyHour);
            }else{
                serviceLog.setWorkHour(Double.parseDouble(serviceLogVo.getWorkHour().trim()));
                serviceLog.setJourneyHour(Double.parseDouble(serviceLogVo.getJourneyHour().trim()));
            }

           // serviceLog.setWorkHour(Double.parseDouble(serviceLogVo.getWorkHour().trim()));
            //serviceLog.setJourneyHour(Double.parseDouble(serviceLogVo.getJourneyHour().trim()));

            serviceLog.setWorkContent(serviceLogVo.getWorkContent());
            serviceLog.setDelFlag("0");
            serviceLog.setCreateTime(new Date());
            serviceLogMapper.insertServiceLog(serviceLog);

            /** 更新操作日志表 */
            BatchLog batchLog = new BatchLog();
            batchLog.setEnginnerId(Long.parseLong(serviceLogVo.getFseId()));
            batchLog.setPlanId(lastPlanId);
            batchLog.setServiceNo(snos[i]);
            batchLog.setCreateTime(new Date());
            batchLog.setBatchType(3L);
            batchLogMapper.insertBatchLog(batchLog);
        }

        return new ResponseWithData<>().success().msg("操作成功").code(200);
    }
    private PlanDetails getPlanDetailsListStateNotOne(String fseId, Long serviceNoticeId){
        PlanDetails searchstPlanDetails =new PlanDetails();
        searchstPlanDetails.setFseId(fseId);
        searchstPlanDetails.setServiceNoticeId(serviceNoticeId);
        List<PlanDetails> planDetailsList = planDetailsMapper.selectStPlanDetailsList(searchstPlanDetails);
        if(planDetailsList!=null){
            for (PlanDetails planDetails : planDetailsList) {
                if("1".equals(planDetails.getState())){
                    //不做操作
                } else{
                    return planDetails;
                }
            }
        }
        return null;
    }

    @Override
    public ResponseWithData<?> findSendTime(String serviceNo, String enginnerId) {
        List<Map<String, Object>> result = serviceLogMapper.findSendTime(serviceNo, enginnerId);
        return new ResponseWithData<>().success(result).msg("操作成功").code(200);
    }

    @Override
    public List<Map<String, Object>> selectUnboundList(Map<String, Object> serviceLog) {
        List<Map<String, Object>> tempList= serviceLogMapper.selectUnboundList(serviceLog);
        return tempList;
    }

    @Override
    public ResponseWithData<?> editServiceLog(Map<String, Object> serviceLogVo) {
        serviceLogMapper.editServiceLog(serviceLogVo);
        return new ResponseWithData<>().success().msg("操作成功").code(200);
    }

    @Override
    public List<Map<String, Object>> selectBoundList(Map<String, Object> serviceLog) {
        return serviceLogMapper.selectBoundList(serviceLog);
    }
}
